﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xna.Framework;

namespace Fusion
{
	public class Stage : Entity
	{
		List<Entity> contents = new List<Entity>();
		List<Entity> trash = new List<Entity>();

		Dictionary<string,List<Entity>> layers = new Dictionary<string,List<Entity>>();
		List<string> layerOrder = new List<string>();

		#region Constructors 

		public Stage()
		{
		}

		#endregion

		#region Common Methods

		public override void Update()
		{
			foreach( Entity entity in contents )
			{
				entity.Update();
				if( entity.active == false )
					trash.Add( entity );
			}

			foreach( Entity entity in trash )
			{
				contents.Remove( entity );
				foreach( List<Entity> layer in layers.Values )
					layer.Remove( entity );
			}
		}

		public override void Draw()
		{
			foreach( string name in layerOrder )
			{
				foreach( Entity entity in layers[name] )
					entity.Draw();
			}
		}

		#endregion

		#region Contents

		public void Add( Entity entity, string layer )
		{
			contents.Add( entity );
			entity.container = this;
			Layer( layer ).Add( entity );
		}

		public List<Entity> Layer( string name )
		{
			if( !layers.ContainsKey( name ) )
			{
				layers.Add( name, new List<Entity>() );
				layerOrder.Add( name );
			}

			return layers[name];
		}

		#endregion

		#region Intersection

		public List<Entity> FindInArea( Vector2 tl, Vector2 br, List<string> layerNames, ref Vector2 minProjection )
		{
			List<Entity> found = new List<Entity>();
			Vector2 proj = Vector2.Zero;
			Vector2 size = br - tl;
			Vector2 center = tl + ( size / 2 );

			foreach( string name in layerNames )
				if( layers.ContainsKey( name ) )
				{
					foreach( Entity entity in layers[name] )
					{
						if( entity.Intersect( center, size, ref proj ) )
							found.Add( entity );

						if( proj.Length() > minProjection.Length() )
							minProjection = proj;
					}
				}

			return found;
		}

		#endregion
	}
}
